#!/usr/bin/python3
import os
import random

import numpy as np
import cv2


class CVPorcess(object):

    def extractP(self, img_path):
        # 提取车牌部分
        # 解决中文名字
        img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
        # cv2.imshow('img', img)
        if img is None:
            return None
        # 转换灰度图
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 边缘检测
        canny = cv2.Canny(gray, 200, 500)
        # cv2.imshow('canny', canny)
        # 轮廓尺寸
        # 图像，轮廓，轮廓的层析结构
        image, contours, hierarchy = cv2.findContours(canny, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        # 车牌宽高以及蓝色区域符合要求
        color_img = None
        for cnt in contours:
            y, x, w, h = cv2.boundingRect(cnt)

            if 2.6 < w / h < 3.4 and h > 10:
                color_img = img[x:(x + h), y:(y + w)]
                # 转换颜色
                hsv = cv2.cvtColor(color_img, cv2.COLOR_BGR2HSV)
                # 蓝色区域
                lower_blue = np.array([100, 47, 47])
                upper_blue = np.array([124, 255, 255])
                # 蓝色掩模
                mask = cv2.inRange(hsv, lower_blue, upper_blue)
                y2, x2 = mask.shape
                # 计算积分积分图像
                sum = cv2.integral(mask)
                # 计算蓝色区域比例
                rate = sum[y2, x2] / (x2 * y2 * 255)
                if rate > 0.5:
                    # print('rate', rate)
                    break
        # cv2.imshow('kk', color_img)
        # cv2.waitKey()
        # cv2.destroyAllWindows()
        num = random.randint(10000, 99999)
        filename = 'm%d.jpg' % num
        flag = cv2.imwrite('static/results/%s' % filename, color_img)
        # print(flag)
        # return color_img, filename
        return filename

    def split_img(self, img_path, filename):
        if img_path is None:
            return None

        # 转换灰度图
        print(img_path)
        img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img_y, img_x = gray.shape
        # 边缘检测
        canny = cv2.Canny(gray, 200, 500)
        # cv2.imshow('kc', canny)
        # cv2.waitKey()
        # 图像，轮廓，轮廓的层析结构
        image, contours, hierarchy = cv2.findContours(canny, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        # kc = cv2.drawContours(img, contours, -1, (0, 255, 0), 1)
        # cv2.imshow('kc', kc)
        # cv2.waitKey()

        color_img = None
        # 最大宽、高
        max_x = 0
        max_y = 0
        canny_list = []
        for cnt in contours:
            y, x, w, h = cv2.boundingRect(cnt)
            # print(x, y, w, h)
            # kc = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 1)
            # cv2.imshow('kc', kc)
            # 高度，宽度符合要求
            if h / img_y > 0.5 and 0.1 < w / img_x < 0.15:
                # print(h, img_y, w, img_x)
                canny_l = canny.copy()
                canny_l[:, :] = 0
                canny_l[x:(x + h), y:(y + w)] = 255
                canny_list.append(canny_l)

                if max_x < w:
                    max_x = w
                if max_y < h:
                    max_y = h
        canny = canny_list[0]
        for cnt in canny_list:
            canny = np.bitwise_or(canny, cnt)
        # 提取出的车牌号码
        num_pic = cv2.bitwise_and(img, img, mask=canny)
        num_file = 'num%s' % filename
        cv2.imwrite('static/results/%s'%num_file, num_pic)

        # 边缘检测
        canny = cv2.Canny(canny, 200, 500)
        # 图像，轮廓，轮廓的层析结构
        image, contours, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # print('max_x', max_x, 'max_y', max_y)
        img_end_list = {}
        gray_end_list = {}
        for cnt in contours:
            x, y, w, h = cv2.boundingRect(cnt)
            # 高度，宽度符合要求
            if h / img_y > 0.5 and w / img_x < 0.5:
                centerX = x + w / 2
                centerY = y + h / 2
                img_end = img[int(centerY - max_y / 2):int(centerY + max_y / 2),
                          int(centerX - max_x / 2):int(centerX + max_x / 2)]
                # 灰度
                img_end_list[centerX] = img_end
                gray_end_list[centerX] = self.change_img(img_end)
        gray_end_list = sorted(gray_end_list.items(), key=lambda x: x[0])
        gray_end_list = [x[1] for x in gray_end_list]
        return img_end_list, gray_end_list, num_file

    def change_img(self, img):
        # 转换灰度图
        # 统一大小 14*24
        img = cv2.resize(img, (14, 24))
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img = cv2.threshold(img, 125, 1, cv2.THRESH_BINARY)
        img_l = []
        for i in img[1]:
            img_l.extend(i)
        return img_l


if __name__ == '__main__':
    k = CVPorcess()
    img = k.split_img('../static/results/m17426.jpg')
